package cc.telecomdigital.tdstock.activity.groups.more.push.util;

import java.util.List;

import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.os.AsyncTask;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.SystemInfo;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.IH_UserClient_HttpRequest_Report;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Services.LS_Authentication.ILS_Authentication_Report;
import cc.telecomdigital.tdstock.Services.LS_ClientSubscriberHandler.ILS_ClientSubscriber_Response;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Response;
import cc.telecomdigital.tdstock.activity.groups.more.push.client.NotificationService;
import cc.telecomdigital.tdstock.activity.groups.more.push.client.ServiceManager;

public class NotificationSwitch
{
	private final static String		TAG		= NotificationSwitch.class
												.getSimpleName();
	// public final static String STOPSERVER = "STOPSERVER";
	private static NotificationSwitch	nswitch	= new NotificationSwitch();

	public static boolean			flag		= false;

	private NotificationSwitch()
	{
	}

	public static NotificationSwitch getInstace()
	{
		return nswitch;
	}

/*	// fetch the lastest url for the context is changed every time;
	private static String getNotificationSettingURL(Context context)
	{
		String result = Data.getNotificationSettingURL(context);
		return result;
	}*/

	/**
	 * 
	 * @param context
	 * @return true is auto 
	 */
	private boolean isAutoStart(Context context)
	{
		android.app.ActivityManager am = (android.app.ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		ComponentName com = am.getRunningTasks(2).get(0).topActivity;

		return !com.getPackageName().equals(context.getPackageName());
	}
	
	
	public void onSwitch(Context context)
	{

		if (null != context)
		{
			try
			{
				ITDLApplication app = (ITDLApplication) context
						.getApplicationContext();
				if (app.getDataMode() == CommonDefn.DataMode.Delay&&!isAutoStart(context))
				{
					TDStockLog.d(TAG, "do nothing under delay mode!");
					return;
				}
				// do nothing under delay mode, modified by haibo in 2012-03-15

				Switch s = new Switch(context);
				s.execute(/* Data.getNotificationSettingURL(context) */);
			}
			catch (Exception e)
			{
				TDStockLog.d(TAG, e.toString());
			}

		}

	}

	// public void onSwitch(Context context, String stopService) {
	// if (null != context) {
	// new Switch(context).execute(ReadNotifitionSetting.getURL(context),
	// stopService);
	// }
	//
	// }

	class Switch /*extends AsyncTask<String, Void, String[]>*/implements
		IH_UserClient_HttpRequest_Report
	{
		private Context		context;
		private ServiceManager	serviceManager;
		private int			retryTimes	= 0;
		private final long		retryLimit	= 20 * 1000;

		public Switch(Context context)
		{
			serviceManager = new ServiceManager(context);
			serviceManager.setNotificationIcon(R.drawable.favicon);
			this.context = context;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */

		private void execute(String... params)
		{

			GetNotificationSwitchDataFromServer();

		}

		/*		protected String[] doInBackground(String... params)
				{
					
					String xmlContent = getContent();
					TDStockLog.d(TAG, null == xmlContent ? "" : xmlContent);
					String notifitionSwitch = "";
					String timeSwitch = "";
					String starttime = "";
					String endtime = "";
					String[] result = new String[4];
					try
					{
						notifitionSwitch = xmlContent.substring(
								xmlContent.indexOf("<EnableNotification>")
										+ "<EnableNotification>".length(),
								xmlContent.indexOf("</EnableNotification>"));
						timeSwitch = xmlContent.substring(
								xmlContent.indexOf("<TimeFiltering>")
										+ "<TimeFiltering>".length(),
								xmlContent.indexOf("</TimeFiltering>"));
						starttime = xmlContent.substring(
								xmlContent.indexOf("<StartTime>")
										+ "<StartTime>".length(),
								xmlContent.indexOf("</StartTime>"));
						endtime = xmlContent.substring(
								xmlContent.indexOf("<EndTime>")
										+ "<EndTime>".length(),
								xmlContent.indexOf("</EndTime>"));
						TDStockLog.d(
								TAG,
								String.format(
										"notifitionSwitch=%s,  timeSwitch=%s, startTime=%s, endTime=%s",
										notifitionSwitch, timeSwitch,
										starttime, endtime));
						result[0] = notifitionSwitch;
						result[1] = timeSwitch;
						result[2] = starttime;
						result[3] = endtime;
					}
					catch (Exception e)
					{
						result[0] = "";
						result[1] = "";
						result[2] = "";
						result[3] = "";
					}
					if (result == null || result.length < 4)
					{
						TDStockLog.e(TAG,
								"the task was canceld  or get a socket time out exception!");
						return null; // socket time out
					}
					return result;
				}*/

		/*		@Override
				protected void onPostExecute(String[] result)
				{
					// don't put the code here for it block the user's action
					super.onPostExecute(result);
					if (result == null || result.length < 4)
					{
						// TDStockLog.d(TAG, "ready to stop service1");
						// stopService(); //don't stop the service if socket is timeout.
					}
					else
					{
						TDStockLog.d(TAG, result[0] + "" + result[1] + ""
								+ result[2] + "" + result[3] + "");
						
						 * if (result[0].equalsIgnoreCase("1") &&
						 * result[1].equalsIgnoreCase("1")) { Date now = new Date(); int
						 * hour = now.getHours(); int minute = now.getMinutes(); int
						 * startHour = Integer.parseInt(result[2].substring(0, 2)); int
						 * startMinute = Integer.parseInt(result[2].substring(2)); int
						 * endHour = Integer.parseInt(result[3].substring(0, 2));
						 * endHour = (endHour == 0 ? 24 : endHour); int endMinute =
						 * Integer.parseInt(result[3].substring(2)); TDStockLog .d(TAG,
						 * String.format(
						 * "startHour=%d,  startMinute=%d,  endHour=%d, endMinute=%d, currHour=%d, currMin=%d"
						 * , startHour, startMinute, endHour, endMinute, hour, minute));
						 * 
						 * int currTime = hour * 60 + minute; int startTime = startHour
						 * * 60 + startMinute; int endTime = endHour * 60 + endMinute;
						 * 
						 * if (currTime >= startTime && currTime < endTime) {
						 * TDStockLog.d(TAG, "ready to start service2"); if
						 * (((ITDLApplication) context.getApplicationContext())
						 * .getDataMode() == DataMode.Realtime) { startService(); } else
						 * { stopService(); } }
						 * 
						 * }
						 
						if ("1".equals(result[0]))
						{
							TDStockLog.d(TAG,
									"警报开关设置为开，值为1，Start Android Push Service");
							startService();
						}
						else if ("0".equals(result[0]))
						{
							TDStockLog.d(TAG,
									"警报开关设置为关，值为0. Ready To Stop Service");
							stopService();
						}
						else
						{
							TDStockLog.e(TAG, "当前开关值为:" + result[0]);
						}
					}
				}
		*/
		/**
		 * stop service
		 */
		private void stopService()
		{
			TDStockLog.d(TAG, "stop service!  ");
			if (isRunNotifitionService())
			{
				TDStockLog.d(TAG, "stop ..........");
				serviceManager.stopService();
			}

		}

		/**
		 * 
		 * start Service
		 */
		private void startService()
		{
			/*
			 * if(!isRunNotifitionService()){ serviceManager.startService();
			 * }else{ if(isConnectionAvailable(context)){
			 * 
			 * }else{ serviceManager.stopService();
			 * serviceManager.startService(); } }
			 */

			NotificationService.flag = flag;
			serviceManager.startService(TAG);
		}

		private void nSwitch(String switchs)
		{
			if ("1".equals(switchs))
			{
				TDStockLog.d(TAG, "警报开关设置为开，值为1，Start Android Push Service");
				startService();
			}
			else if ("0".equals(switchs))
			{
				TDStockLog.d(TAG, "警报开关设置为关，值为0. Ready To Stop Service");
				stopService();
			}
			else
			{
				TDStockLog.e(TAG, "当前开关值为:" + switchs);
			}
		}

		private boolean isRunNotifitionService()
		{
			boolean flag = false;
			android.app.ActivityManager am = (android.app.ActivityManager) context
					.getSystemService(Context.ACTIVITY_SERVICE);
			List<RunningServiceInfo> lists = am.getRunningServices(300);
			for (int i = 0; i < lists.size(); i++)
			{
				if (lists.get(i).service.getPackageName().equalsIgnoreCase(
				/* "cc.telecomdigital.tdstock" */context.getPackageName()))
				{
					context.getSystemService(/* "cc.telecomdigital.tdstock" */context
							.getPackageName());
					flag = true;
				}
			}
			return flag;
		}

		/*
		 * private boolean isConnectionAvailable(final Context context){
		 * ServiceConnection serverConn=new ServiceConnection() {
		 * 
		 * @Override public void onServiceDisconnected(ComponentName name) { //
		 * TODO Auto-generated method stub
		 * 
		 * }
		 * 
		 * @Override public void onServiceConnected(ComponentName name, IBinder
		 * service) { // TODO Auto-generated method stub TestConnection
		 * conn=TestConnection.Stub.asInterface(service); try { if(conn!=null){
		 * NotificationSwitch.flag=conn.getConnection(); Toast.makeText(context,
		 * "ccccccc", Toast.LENGTH_SHORT); } } catch (RemoteException e) { //
		 * TODO Auto-generated catch block e.printStackTrace(); } } }; return
		 * NotificationSwitch.flag; }
		 */
		/*		public String getContent( String url )
				{
					String tmpContent = null;

					String settingUrl = getNotificationSettingURL(context);
					TDStockLog.d(TAG, "setting URL:" + settingUrl);

					if (SystemInfo.isNetworkingConnected(context))
					{
						tmpContent =  DataRead.getContentFromURL(url); DataRead
								.getContentFromURL(settingUrl);
					}

					long startTime = System.currentTimeMillis();

					retryTimes = 0;
					while (tmpContent == null
							&& (System.currentTimeMillis() - startTime <= retryLimit))
					{
						if (!SystemInfo.isNetworkingConnected(context))
						{
							TDStockLog.d(TAG, "检测到没有网络, 正在准备重试:当前重试次数:"
									+ retryTimes++);
							Thread.yield();
							continue;
						}
						else
						{
							settingUrl = getNotificationSettingURL(context);
							TDStockLog.d(TAG, "setting URL:" + settingUrl);
							TDStockLog.d(TAG, "检测到有网络了, 正在准备重试:当前重试次数:"
									+ retryTimes++);
							tmpContent =  DataRead.getContentFromURL(url); DataRead
									.getContentFromURL(settingUrl);
							TDStockLog.d(TAG, "重试结果:" + tmpContent == null ? "失败!"
									: "成功!");
						}

					}

					
					 * for (int i = 0; i < 15; i++) {
					 * 
					 * if(temp!=null){ break; }else{ Log.d(TAG, "正在准备重试:当前重试次数:" + i );
					 * 
					 * if(SystemInfo.isNetworkingConnected(context)){ temp=
					 * DataRead.getContentFromURL(url); } else { try {
					 * Thread.sleep(2000); } catch (InterruptedException e) { // TODO
					 * Auto-generated catch block e.printStackTrace(); } } } }
					 
					return tmpContent;

				}*/

		private H_CODE GetNotificationSwitchDataFromServer()
		{
			return HttpAppInfo.GetNotificationSwitch(context, this,
					"Notification");
		}

		/* (non-Javadoc)
		 * @see cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.IH_UserClient_HttpRequest_Report#H_UserClient_HttpRequest_Response(cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result)
		 */
		@Override
		public void H_UserClient_HttpRequest_Response(
				H_UserClient_HttpRequest_Result iResult)
		{
			// TODO Auto-generated method stub
			if (!iResult.MStatus.equals("0"))
			{

				return;
			}

			if (iResult.seqID.equals("Notification"))
			{
				List<String[]> notifications = iResult.contentStores;
				String switchs = notifications.get(0)[0];
				nSwitch(switchs);
			}
		}
	}

}